<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="题目ID" prop="questionId">
          <el-input
            v-model="queryParams.questionId"
            placeholder="请输入题目ID"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="题目内容" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入题目内容"
            clearable
            prefix-icon="el-icon-search"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="box-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span class="card-title">解析列表</span>
        <div class="action-buttons">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['question:analysis:add']"
          >新增</el-button>
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['question:analysis:edit']"
          >修改</el-button>
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['question:analysis:remove']"
          >删除</el-button>
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['question:analysis:export']"
          >导出</el-button>
          <el-button
            :type="showDeleted ? 'warning' : 'info'"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="toggleRecycleBin"
          >{{ showDeleted ? '返回列表' : '回收站' }}</el-button>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="analysisList"
        @selection-change="handleSelectionChange"
        border
        stripe
        highlight-current-row
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="解析ID" align="center" prop="id" width="80" />
        <el-table-column label="题目内容" align="left" prop="dtQuestion.title" :show-overflow-tooltip="true" min-width="300">
          <template slot-scope="scope">
            <div class="question-content" v-html="scope.row.dtQuestion.title"></div>
          </template>
        </el-table-column>
        <el-table-column label="解析内容" align="left" prop="content" min-width="250">
          <template slot-scope="scope">
            <div class="analysis-content" v-html="scope.row.content"></div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="isDeleted" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.isDeleted"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template slot-scope="scope">
            <template v-if="!showDeleted">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['question:analysis:edit']"
              >修改</el-button>
              <el-divider direction="vertical"></el-divider>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['question:analysis:remove']"
              >删除</el-button>
            </template>
            <template v-else>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-refresh"
                @click="handleRestore(scope.row)"
                v-hasPermi="['question:analysis:edit']"
              >恢复</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改答案解析对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item v-if="form.id" label="解析ID">
          <el-input v-model="form.id" disabled />
        </el-form-item>
        <el-form-item label="题目ID" prop="questionId">
          <el-input 
            v-model="form.questionId" 
            placeholder="请输入题目ID" 
            style="width: 200px"
            :disabled="form.id != null"
            @change="handleQuestionIdChange"
          />
        </el-form-item>
        <el-form-item label="题目内容">
          <div class="question-content" v-html="questionTitle"></div>
        </el-form-item>
        <el-form-item label="解析内容" prop="content">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="状态" prop="isDeleted">
          <el-select v-model="form.isDeleted" placeholder="请选择状态" style="width: 100%">
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAnalysis, getAnalysis, delAnalysis, addAnalysis, updateAnalysis } from "@/api/question/analysis";
import { listQuestions, getQuestions } from "@/api/question/questions";

export default {
  name: "Analysis",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 答案解析表格数据
      analysisList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        questionId: null,
        title: null,
        isDeleted: '0'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        questionId: [
          { required: true, message: "题目ID不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "解析内容不能为空", trigger: "blur" }
        ]
      },
      questionTitle: '',
      // 题目选项
      questionOptions: [],
      showDeleted: false,
    };
  },
  created() {
    this.getList();
    this.getQuestionOptions();
  },
  methods: {
    /** 查询答案解析列表 */
    getList() {
      this.loading = true;
      listAnalysis(this.queryParams).then(response => {
        this.analysisList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.analysisList = [];
        this.total = 0;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 重置表单 */
    reset() {
      this.form = {
        id: null,
        questionId: null,
        content: null,
        isDeleted: 0
      };
      this.questionTitle = '';
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 保持当前回收站状态
      this.queryParams.isDeleted = this.showDeleted ? '1' : '0';
      // 重置分页参数
      this.queryParams.pageNum = 1;
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加答案解析";
      // 清空题目内容
      this.questionTitle = '';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (!row || !row.id) {
        this.$modal.msgError("数据异常");
        return;
      }

      this.reset();
      this.open = true;
      this.title = "修改答案解析";
      
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      getAnalysis(row.id)
        .then(response => {
          loading.close();
          
          if (!response || !response.data) {
            throw new Error('未获取到数据');
          }

          const { id, questionId, content, isDeleted } = response.data;

          this.form = {
            id,
            questionId,
            content: content || '',
            isDeleted: parseInt(isDeleted || '0')
          };

          if (questionId) {
            this.handleQuestionIdChange(questionId);
          }
        })
        .catch(error => {
          loading.close();
          console.error("获取数据失败:", error);
          this.$modal.msgError("操作失败");
          this.open = false;
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;

        // 添加 loading
        const loading = this.$loading({
          lock: true,
          text: '提交中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        // 检查题目ID是否已存在解析（只检查未删除的记录）
        listAnalysis({
          questionId: this.form.questionId,
          isDeleted: '0',
          pageSize: 1
        }).then(response => {
          const existingAnalysis = response.rows.find(item => 
            item.questionId === this.form.questionId && item.id !== this.form.id
          );

          if (existingAnalysis) {
            loading.close();
            this.$modal.msgError("该题目已存在解析");
            return;
          }

          // 不存在重复，继续提交
          const request = this.form.id ? updateAnalysis(this.form) : addAnalysis(this.form);
          
          request.then(response => {
            loading.close();
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          }).catch(() => {
            loading.close();
            this.$modal.msgError("操作失败");
          });
        }).catch(() => {
          loading.close();
          this.$modal.msgError("操作失败");
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认永久删除该解析？该操作不可恢复！').then(function() {
        return delAnalysis(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('question/analysis/export', {
        ...this.queryParams
      }, `analysis_${new Date().getTime()}.xlsx`)
    },
    /** 获取题目选项 */
    getQuestionOptions() {
      listQuestions({ pageSize: 999999 }).then(response => {
        this.questionOptions = response.rows;
      });
    },
    /** 题目ID变化时获取题目内容 */
    handleQuestionIdChange(value) {
      if (value) {
        getQuestions(value).then(response => {
          if (response.data) {
            this.questionTitle = response.data.title;
          } else {
            this.$modal.msgError("未找到相关题目");
            this.questionTitle = '';
          }
        }).catch(() => {
          this.questionTitle = '';
        });
      } else {
        this.questionTitle = '';
      }
    },
    /** 切换回收站显示状态 */
    toggleRecycleBin() {
      this.showDeleted = !this.showDeleted;
      // 重置分页参数
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.queryParams.isDeleted = this.showDeleted ? '1' : '0';
      // 重置选中状态
      this.ids = [];
      this.single = true;
      this.multiple = true;
      // 重新获取列表
      this.getList();
    },
    /** 恢复按钮操作 */
    handleRestore(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认恢复解析编号为"' + id + '"的数据项？').then(async () => {
        // 获取解析详细信息
        const response = await getAnalysis(id);
        // 修改状态为0（正常）
        const data = {
          ...response.data,
          isDeleted: 0
        };
        // 调用修改接口
        return updateAnalysis(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("恢复成功");
      }).catch(() => {});
    },
  }
};
</script>

<style scoped>
.search-card {
  margin-bottom: 16px;
  border-radius: 4px;
}

.box-card {
  margin-bottom: 16px;
  border-radius: 4px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2f3d;
}

.action-buttons {
  float: right;
}

.question-content {
  padding: 8px 12px;
  line-height: 1.6;
  text-align: left;
  background-color: #f5f7fa;
  border-radius: 4px;
  min-height: 24px;
}

.analysis-content {
  padding: 8px 12px;
  line-height: 1.6;
  text-align: left;
  background-color: #fdf6ec;
  border-radius: 4px;
  color: #e6a23c;
}

.el-card {
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08) !important;
}

.el-card :deep(.el-card__header) {
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

.el-table {
  margin: 8px 0;
}

.el-table :deep(th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
}

.el-table :deep(td) {
  padding: 8px 0;
}

.el-tag {
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

.el-divider--vertical {
  margin: 0 8px;
}

/* 表格hover效果 */
.el-table :deep(tbody tr:hover) td {
  background-color: #fdf6ec !important;
}

/* 输入框图标颜色 */
.el-input :deep(.el-input__icon) {
  color: #909399;
}

/* 表单项间距 */
.el-form-item {
  margin-bottom: 16px;
}
</style>
